6 * @author Zhengzhu Feng <zhengzhu@gmail.com>
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
10 class LanguageConverter
{
11 var $mPreferredVariant='';
12 var $mMainLanguageCode;
13 var $mVariants, $mVariantFallbacks;
14 var $mTablesLoaded = false;
16 var $mTitleDisplay='';
17 var $mDoTitleConvert=true, $mDoContentConvert=true;
25 * @param string $maincode the main language code of this language
26 * @param array $variants the supported variants of this language
27 * @param array $variantfallback the fallback language of each variant
28 * @param array $markup array defining the markup used for manual conversion
29 * @param array $flags array defining the custom strings that maps to the flags
32 function LanguageConverter($langobj, $maincode,
34 $variantfallbacks=array(),
38 $this->mLangObj
= $langobj;
39 $this->mMainLanguageCode
= $maincode;
40 $this->mVariants
= $variants;
41 $this->mVariantFallbacks
= $variantfallbacks;
42 $this->mCacheKey
= $wgDBname . ":conversiontables";
43 $m = array('begin'=>'-{', 'flagsep'=>'|', 'codesep'=>':',
44 'varsep'=>';', 'end'=>'}-');
45 $this->mMarkup
= array_merge($m, $markup);
46 $f = array('A'=>'A', 'T'=>'T');
47 $this->mFlags
= array_merge($f, $flags);
53 function getVariants() {
54 return $this->mVariants
;
58 * in case some variant is not defined in the markup, we need
59 * to have some fallback. for example, in zh, normally people
60 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
61 * when zh-sg is preferred but not defined, we will pick zh-cn
62 * in this case. right now this is only used by zh.
64 * @param string $v the language code of the variant
65 * @return string the code of the fallback language or false if there is no fallback
68 function getVariantFallback($v) {
69 return $this->mVariantFallbacks
[$v];
74 * get preferred language variants.
75 * @return string the preferred language code
78 function getPreferredVariant() {
79 global $wgUser, $wgRequest;
81 if($this->mPreferredVariant
)
82 return $this->mPreferredVariant
;
84 // see if the preference is set in the request
85 $req = $wgRequest->getText( 'variant' );
86 if( in_array( $req, $this->mVariants
) ) {
87 $this->mPreferredVariant
= $req;
91 // get language variant preference from logged in users
92 if(is_object($wgUser) && $wgUser->isLoggedIn() ) {
93 $this->mPreferredVariant
= $wgUser->getOption('variant');
96 # FIXME rewrite code for parsing http header. The current code
97 # is written specific for detecting zh- variants
98 if( !$this->mPreferredVariant
) {
99 // see if some zh- variant is set in the http header,
100 $this->mPreferredVariant
=$this->mMainLanguageCode
;
101 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
102 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
103 $zh = strstr($header, 'zh-');
105 $this->mPreferredVariant
= substr($zh,0,5);
110 return $this->mPreferredVariant
;
114 * dictionary-based conversion
116 * @param string $text the text to be converted
117 * @param string $toVariant the target language code
118 * @return string the converted text
121 function autoConvert($text, $toVariant=false) {
122 $fname="LanguageConverter::autoConvert";
124 wfProfileIn( $fname );
126 if(!$this->mTablesLoaded
)
130 $toVariant = $this->getPreferredVariant();
131 if(!in_array($toVariant, $this->mVariants
))
135 $reg = '/<[^>]+>|&[a-z#][a-z0-9]+;|'.UNIQ_PREFIX
.'-[a-zA-Z0-9]+/';
136 $matches = preg_split($reg, $text, -1, PREG_SPLIT_OFFSET_CAPTURE
);
139 $m = array_shift($matches);
140 $ret = strtr($m[0], $this->mTables
[$toVariant]);
141 $mstart = $m[1]+
strlen($m[0]);
142 foreach($matches as $m) {
143 $ret .= substr($text, $mstart, $m[1]-$mstart);
144 $ret .= strtr($m[0], $this->mTables
[$toVariant]);
145 $mstart = $m[1] +
strlen($m[0]);
147 wfProfileOut( $fname );
152 * convert text to all supported variants
154 * @param string $text the text to be converted
155 * @return array of string
158 function autoConvertToAllVariants($text) {
159 $fname="LanguageConverter::autoConvertToAllVariants";
160 wfProfileIn( $fname );
161 if( !$this->mTablesLoaded
)
165 foreach($this->mVariants
as $variant) {
166 $ret[$variant] = strtr($text, $this->mTables
[$variant]);
168 wfProfileOut( $fname );
173 * convert text to different variants of a language. the automatic
174 * conversion is done in autoConvert(). here we parse the text
175 * marked with -{}-, which specifies special conversions of the
176 * text that can not be accomplished in autoConvert()
178 * syntax of the markup:
179 * -{code1:text1;code2:text2;...}- or
180 * -{text}- in which case no conversion should take place for text
182 * @param string $text text to be converted
183 * @param bool $isTitle whether this conversion is for the article title
184 * @return string converted text
187 function convert( $text , $isTitle=false) {
188 global $wgDisableLangConversion;
190 if($wgDisableLangConversion)
193 $mw =& MagicWord
::get( MAG_NOTITLECONVERT
);
194 if( $mw->matchAndRemove( $text ) )
195 $this->mDoTitleConvert
= false;
197 $mw =& MagicWord
::get( MAG_NOCONTENTCONVERT
);
198 if( $mw->matchAndRemove( $text ) ) {
199 $this->mDoContentConvert
= false;
202 // no conversion if redirecting
203 $mw =& MagicWord
::get( MAG_REDIRECT
);
204 if( $mw->matchStart( $text ))
208 if( !$this->mDoTitleConvert
) {
209 $this->mTitleDisplay
= $text;
212 if( !empty($this->mTitleDisplay
))
213 return $this->mTitleDisplay
;
216 $isredir = $wgRequest->getText( 'redirect', 'yes' );
217 $action = $wgRequest->getText( 'action' );
218 if ( $isredir == 'no' ||
$action == 'edit' ) {
222 $this->mTitleDisplay
= $this->autoConvert($text);
223 return $this->mTitleDisplay
;
227 if( !$this->mDoContentConvert
)
230 $plang = $this->getPreferredVariant();
231 $fallback = $this->mVariantFallbacks
[$plang];
233 $tarray = explode($this->mMarkup
['begin'], $text);
234 $tfirst = array_shift($tarray);
235 $text = $this->autoConvert($tfirst);
236 foreach($tarray as $txt) {
237 $marked = explode($this->mMarkup
['end'], $txt);
239 $tt = explode($this->mMarkup
['flagsep'], $marked[0], 2);
241 if(sizeof($tt) == 2) {
242 $f = explode($this->mMarkup
['varsep'], $tt[0]);
245 if(array_key_exists($ff, $this->mFlags
) &&
246 !array_key_exists($this->mFlags
[$ff], $flags))
247 $flags[] = $this->mFlags
[$ff];
254 #FIXME: may cause trouble here...
255 //strip since it interferes with the parsing, plus,
256 //all spaces should be stripped in this tag anyway.
257 $rules = str_replace(' ', '', $rules);
259 $carray = $this->parseManualRule($rules, $flags);
261 if(array_key_exists($plang, $carray))
262 $disp = $carray[$plang];
263 else if(array_key_exists($fallback, $carray))
264 $disp = $carray[$fallback];
266 if(in_array('T', $flags))
267 $this->mTitleDisplay
= $disp;
271 if(in_array('A', $flags)) {
272 /* modify the conversion table for this session*/
274 /* fill in the missing variants, if any,
276 foreach($this->mVariants
as $v) {
277 if(!array_key_exists($v, $carray)) {
278 $vf = $this->getVariantFallback($v);
279 if(array_key_exists($vf, $carray))
280 $carray[$v] = $carray[$vf];
284 foreach($this->mVariants
as $vfrom) {
285 if(!array_key_exists($vfrom, $carray))
287 foreach($this->mVariants
as $vto) {
290 if(!array_key_exists($vto, $carray))
292 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
301 if(array_key_exists(1, $marked))
302 $text .= $this->autoConvert($marked[1]);
309 * parse the manually marked conversion rule
310 * @param string $rule the text of the rule
311 * @return array of the translation in each variant
314 function parseManualRule($rules, $flags=array()) {
316 $choice = explode($this->mMarkup
['varsep'], $rules);
318 if(sizeof($choice) == 1) {
319 /* a single choice */
320 foreach($this->mVariants
as $v)
321 $carray[$v] = $choice[0];
324 foreach($choice as $c) {
325 $v = explode($this->mMarkup
['codesep'], $c);
326 if(sizeof($v) != 2) // syntax error, skip
328 $carray[trim($v[0])] = trim($v[1]);
335 * if a language supports multiple variants, it is
336 * possible that non-existing link in one variant
337 * actually exists in another variant. this function
338 * tries to find it. See e.g. LanguageZh.php
340 * @param string $link the name of the link
341 * @param mixed $nt the title object of the link
342 * @return null the input parameters may be modified upon return
345 function findVariantLink( &$link, &$nt ) {
346 static $count=0; //used to limit this operation
347 static $cache=array();
348 global $wgDisableLangConversion;
349 $pref = $this->getPreferredVariant();
353 $variants = $this->autoConvertToAllVariants($link);
354 if($variants == false) //give up
356 foreach( $variants as $v ) {
357 if(isset($cache[$v]))
360 $varnt = Title
::newFromText( $v );
361 if( $varnt && $varnt->getArticleID() > 0 ) {
363 if( !$wgDisableLangConversion && $pref != 'zh' )
371 * returns language specific hash options
375 function getExtraHashOptions() {
376 $variant = $this->getPreferredVariant();
377 return '!' . $variant ;
381 * get title text as defined in the body of the article text
385 function getParsedTitle() {
386 return $this->mTitleDisplay
;
390 * a write lock to the cache
394 function lockCache() {
397 for($i=0; $i<30; $i++
) {
398 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
410 function unlockCache() {
412 $wgMemc->delete($this->mCacheKey
. "lock");
417 * Load default conversion tables
418 * This method must be implemented in derived class
422 function loadDefaultTables() {
423 $name = get_class($this);
424 die("Must implement loadDefaultTables() method in class $name");
428 * load conversion tables either from the cache or the disk
431 function loadTables($fromcache=true) {
433 if( $this->mTablesLoaded
)
435 $this->mTablesLoaded
= true;
437 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
438 if( !empty( $this->mTables
) ) //all done
441 // not in cache, or we need a fresh reload.
442 // we will first load the default tables
443 // then update them using things in MediaWiki:Zhconversiontable/*
444 global $wgMessageCache;
445 $this->loadDefaultTables();
446 foreach($this->mVariants
as $var) {
447 $cached = $this->parseCachedTable($var);
448 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
451 $this->postLoadTables();
453 if($this->lockCache()) {
454 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
455 $this->unlockCache();
460 * Hook for post processig after conversion tables are loaded
463 function postLoadTables() {}
466 function updateTablexxxx($code, $table) {
468 if(!$this->mTablesLoaded
)
471 $this->mTables
[$code] = array_merge($this->mTables
[$code], $table);
472 if($this->lockCache()) {
473 $wgMemc->delete($this->mCacheKey
);
474 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
475 $this->unlockCache();
480 * Reload the conversion tables
484 function reloadTables() {
486 unset($this->mTables
);
487 $this->mTablesLoaded
= false;
488 $this->loadTables(false);
493 * parse the conversion table stored in the cache
495 * the tables should be in blocks of the following form:
503 * to make the tables more manageable, subpages are allowed
504 * and will be parsed recursively if $recursive=true
508 function parseCachedTable($code, $subpage='', $recursive=true) {
509 global $wgMessageCache;
510 static $parsed = array();
512 if(!is_object($wgMessageCache))
515 $key = 'Conversiontable/'.$code;
517 $key .= '/' . $subpage;
519 if(array_key_exists($key, $parsed))
523 $txt = $wgMessageCache->get( $key, true, true, true );
525 // get all subpage links of the form
526 // [[MediaWiki:conversiontable/zh-xx/...|...]]
527 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
528 $subs = explode('[[', $txt);
530 foreach( $subs as $sub ) {
531 $link = explode(']]', $sub, 2);
532 if(count($link) != 2)
534 $b = explode('|', $link[0]);
535 $b = explode('/', trim($b[0]), 3);
541 if($b[0] == $linkhead && $b[1] == $code) {
542 $sublinks[] = $sublink;
547 // parse the mappings in this page
548 $blocks = explode($this->mMarkup
['begin'], $txt);
549 array_shift($blocks);
551 foreach($blocks as $block) {
552 $mappings = explode($this->mMarkup
['end'], $block, 2);
553 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
554 $table = explode( ';', $stripped );
555 foreach( $table as $t ) {
556 $m = explode( '=>', $t );
557 if( count( $m ) != 2)
559 // trim any trailling comments starting with '//'
560 $tt = explode('//', $m[1], 2);
561 $ret[trim($m[0])] = trim($tt[0]);
564 $parsed[$key] = true;
567 // recursively parse the subpages
569 foreach($sublinks as $link) {
570 $s = $this->parseCachedTable($code, $link, $recursive);
571 $ret = array_merge($ret, $s);
578 * Enclose a string with the "no conversion" tag. This is used by
579 * various functions in the Parser
581 * @param string $text text to be tagged for no conversion
582 * @return string the tagged text
584 function markNoConversion($text) {
585 # don't mark if already marked
586 if(strpos($text, $this->mMarkup
['begin']) ||
587 strpos($text, $this->mMarkup
['end']))
590 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
595 * hook to refresh the cache of conversion tables when
596 * MediaWiki:conversiontable* is updated
599 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
600 $titleobj = $article->getTitle();
601 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
603 global $wgContLang; // should be an LanguageZh.
604 if(get_class($wgContLang) != 'languagezh')
607 $title = $titleobj->getDBkey();
608 $t = explode('/', $title, 3);
610 if( $c > 1 && $t[0] == 'Conversiontable' ) {
611 if(in_array($t[1], $this->mVariants
)) {
612 $this->reloadTables();